//
//  LeftViewController.m
//  Meng
//
//  Created by dllo on 15/10/6.
//  Copyright (c) 2015年 ljw. All rights reserved.
//

#import "LeftViewController.h"
#import "LikeViewController.h"
#import "FeedBackViewController.h"
@interface LeftViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UITableView *tableview;

@property (nonatomic, assign) NSMutableArray *imgArr;

@property (nonatomic, assign) NSMutableArray *titleArr;

@property (nonatomic, assign) BOOL night;

@property (nonatomic, retain) NSString *cachesPath;

@property (nonatomic, retain) NSMutableArray *cachesArr;
@end

@implementation LeftViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([[defaults objectForKey:@"day"] isEqualToString:@"2"]) {
        self.night = 0;
    } else {
        self.night = 1;
    }

    self.view.backgroundColor = [UIColor clearColor];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"top.png"] forBarMetrics:UIBarMetricsDefault];
    
    self.imgArr = @[@"clean.png",@"black.png",@"collect.png",@"our"].mutableCopy;
    self.titleArr = @[@"清除缓存", @"夜间模式", @"收藏", @"关于我们"].mutableCopy;
    
    [self ViewSubview];
    
}
- (void)ViewSubview
{
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(W / 9.375, H / 5.1, W / 1.875, H / 1.6675) style:UITableViewStyleGrouped];
    self.tableview.dataSource = self;
    self.tableview.delegate = self;
    self.tableview.rowHeight = 65;
    self.tableview.separatorStyle = NO;
    self.tableview.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableview];
    
    [self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    
    cell.imageView.frame = CGRectMake(W / 75, W / 75, W / 9.375, W / 9.375);
    
    cell.backgroundColor = [UIColor clearColor];
    
    cell.textLabel.text = [self.titleArr objectAtIndex:indexPath.row];
    
    cell.textLabel.textColor = [UIColor colorWithRed:204 / 255.0 green:51 / 255.0 blue:255 / 255.0 alpha:1];
    
    cell.imageView.image = [UIImage imageNamed:[self.imgArr objectAtIndex:indexPath.row]];
    
    cell.selectionStyle = 0;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        /* 提示框 */
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否清除缓存" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        /* 添加action */
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            /* 文件管理者, 清理缓存时直接把 Caches 文件删除 */
            
            
            /* 查找到缓存文件的方法 */
            self.cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            
            [self fileSizeAtPath:self.cachesPath];
            NSLog(@"qqqqqqqqqqqqqq");
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"共清除%0.2fM缓存", [self folderSizeAtPath:self.cachesPath]] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *yes = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
                NSFileManager *fileManager = [NSFileManager defaultManager];
                NSError *error = nil;
                
                [fileManager removeItemAtPath:self.cachesPath error:&error];
                
                
            }];
            [alert addAction:yes];
            [self presentViewController:alert animated:YES completion:^{
                
                
            }];
        }];
        
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }];
        
        [alert addAction:action];
        [alert addAction:cancleAction];
        
    }else if (indexPath.row == 1){
        
        /* 控制中心: 夜间模式 */
        
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        self.night = !self.night;
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        if (self.night == 1) {
            NSNumber *nub = [[NSNumber alloc] initWithFloat:0];
            [center postNotificationName:@"nightModel" object:nub];
            [user setObject:@"1" forKey:@"day"];
        }else{
            NSNumber *nub = [[NSNumber alloc] initWithFloat:0.5];
            [center postNotificationName:@"nightModel" object:nub];
            [user setObject:@"2" forKey:@"day"];            
        }
    }
    else if (indexPath.row == 2){
        
        LikeViewController *like = [[LikeViewController alloc] init];
        
        [self presentViewController:like animated:YES completion:^{
            
        }];
        
    }
    
    else if (indexPath.row == 3){
        
        FeedBackViewController *feed = [[FeedBackViewController alloc] init];
        [self presentViewController:feed animated:YES completion:^{
            
        }];
    }
    
    
}

- (long) fileSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}


#pragma mark - 计算清除文件夹的大小

- (float ) folderSizeAtPath:(NSString*) folderPath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath])
        return 0;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString* fileName;
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0 * 1024.0);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
